<?php
/**
 * 路由缓存命令：替代 php artisan route:cache
 */

namespace Jammiest\SwigeCore\Console\Commands\Cache;

use Jammiest\SwigeCore\Console\Commands\Command;
use Jammiest\SwigeCore\Tools\Path;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;


#[AsCommand(name: 'route:cache')]
class RouteCommand extends Command
{

    protected function configure()
    {
        $this->setDescription('缓存路由文件中');
    }

    protected function execute(InputInterface $input, OutputInterface $output):int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('缓存路由文件');
        
        try {
            $cacheFile = Path::getBasePath('storage/framework/cache/routes.php');
            // $cacheFile = storage_path('framework/cache/routes.php');
            $cacheDir = dirname($cacheFile);
            
            if (!is_dir($cacheDir)) {
                mkdir($cacheDir, 0755, true);
            }
            
            // 加载路由配置
            $routes = $this->loadRoutes();
            
            // 写入缓存文件
            $cacheContent = '<?php return ' . var_export($routes, true) . ';';
            file_put_contents($cacheFile, $cacheContent);
            
            $io->success('路由缓存已生成: ' . $cacheFile);
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $io->error('路由缓存失败: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    private function loadRoutes()
    {
        $routes = [];
        $routeFiles = glob(Path::getBasePath('routes/*.php'));
        // $routeFiles = glob(base_path('routes/*.php'));
        
        foreach ($routeFiles as $file) {
            $routes[basename($file, '.php')] = $this->parseRoutesFromFile($file);
        }
        
        return $routes;
    }

    private function parseRoutesFromFile($file)
    {
        // 简单的路由解析逻辑
        $content = file_get_contents($file);
        preg_match_all('/Route::(\w+)\([\'"]([^\'"]+)[\'"]/', $content, $matches);
        
        $routes = [];
        foreach ($matches[1] as $index => $method) {
            $routes[] = [
                'method' => strtoupper($method),
                'path' => $matches[2][$index],
                'file' => basename($file)
            ];
        }
        
        return $routes;
    }
}